package com.yourenbang.lingyun.transaction.web.service.impl.pay.transaction;

import cn.hutool.core.collection.CollectionUtil;
import com.yourenbang.lingyun.constants.BizCodeMessages;
import com.yourenbang.lingyun.constants.enums.ChannelIdEnums;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.constants.enums.table.TerminalEnum;
import com.yourenbang.lingyun.core.config.datasource.DataSources;
import com.yourenbang.lingyun.core.config.datasource.RoutingDataSource;
import com.yourenbang.lingyun.core.message.Result;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.domain.*;
import com.yourenbang.lingyun.mapper.Terminal21Mapper;
import com.yourenbang.lingyun.mapper.TerminalHistory21Mapper;
import com.yourenbang.lingyun.mapper.UserMerchantRecommend21Mapper;
import com.yourenbang.lingyun.transaction.mapper.TransactionPayTransactionMapper;
import com.yourenbang.lingyun.transaction.util.PayTransactionUtil;
import com.yourenbang.terminal.api.service.RpcYxyTerminalService;
import com.yourenbang.transaction.api.model.dto.fund.*;
import com.yourenbang.transaction.api.model.dto.pay.*;
import com.yourenbang.transaction.api.model.vo.pay.*;
import com.yourenbang.transaction.api.service.pay.transaction.TransactionApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class TransactionApiServiceImpl implements TransactionApiService {

    @Autowired
    private TransactionPayTransactionMapper transactionPayTransactionMapper;
    @Autowired
    RpcYxyTerminalService rpcYxyTerminalService;
    @Autowired
    UserMerchantRecommend21Mapper userMerchantRecommend21Mapper;
    @Autowired
    TerminalHistory21Mapper terminalHistory21Mapper;
    @Autowired
    Terminal21Mapper terminal21Mapper;
    /**
     * 实时达标金额
     */
    @Override
    @RoutingDataSource(DataSources.SLAVE_DB)
    public Result<ReachAmtVO> reachAmt(ReachAmtDTO dto) {
        KLog.info("[实时达标金额]入参:{}", dto.toJSON());
        ReachAmtVO reachAmtVO = new ReachAmtVO();
        if (PlatNoEnums.KLKS.isEquals(dto.getPlatNo())) {
            if (ChannelIdEnums.epos.isEquals(dto.getChannelId())
                    || ChannelIdEnums.p35.isEquals(dto.getChannelId())
                    || ChannelIdEnums.k40.isEquals(dto.getChannelId())
                    || ChannelIdEnums.k45.isEquals(dto.getChannelId())
            ) {
                if (dto.getStage() != null && dto.getStage() == 1 && !ChannelIdEnums.p35.isEquals(dto.getChannelId())){
                    reachAmtVO.setReachAmt(transactionPayTransactionMapper.eposPledgeAmtByChannelId(dto.getUserBaseId(),
                            dto.getBeginTime(), dto.getEndTime(), PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()),
                            dto.getChannelId()));
                }else{
                    reachAmtVO.setReachAmt(transactionPayTransactionMapper.eposReachAmt(dto.getUserBaseId(),
                            dto.getBeginTime(), dto.getEndTime(), PayTransactionConfig.getTransTableIndex(dto.getUserBaseId())));
                }
            } else if (ChannelIdEnums.epos_p30.isEquals(dto.getChannelId())) {
                if (dto.getStage() != null && dto.getStage() == 1) {
                    reachAmtVO.setReachAmt(transactionPayTransactionMapper.eposP30ReachAmt(dto.getUserBaseId(), dto.getBeginTime(), dto.getEndTime(), PayTransactionConfig.getTransTableIndex(dto.getUserBaseId())));
                } else {
                    reachAmtVO.setReachAmt(transactionPayTransactionMapper.eposP30ReachAmtNo38(dto.getUserBaseId(), dto.getBeginTime(), dto.getEndTime(), PayTransactionConfig.getTransTableIndex(dto.getUserBaseId())));
                }
            }
        } else if (PlatNoEnums.YXY.isEquals(dto.getPlatNo())) {
            if (dto.getStage() !=null && dto.getStage() == 1) {
                if (ChannelIdEnums.yxy_lkl_p42.isEquals(dto.getChannelId())){
                    reachAmtVO.setReachAmt(transactionPayTransactionMapper.yxyP42ActiveAmtByChannelId(dto.getUserBaseId(),
                            dto.getBeginTime(), dto.getEndTime(), PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()),
                            dto.getChannelId()));
                } else{
                    reachAmtVO.setReachAmt(transactionPayTransactionMapper.yxyEposPledgeAmtByChannelId(dto.getUserBaseId(),
                            dto.getBeginTime(), dto.getEndTime(), PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()),
                            dto.getChannelId()));
                }
            } else {
                if (ChannelIdEnums.isEqualsAny(dto.getChannelId(), ChannelIdEnums.yxy_sft_s40, ChannelIdEnums.YXY_SFT_S50)){
                    //盛付通算押金
                    reachAmtVO.setReachAmt(transactionPayTransactionMapper.yxyEposReachAmtByChannelIdIncluePledge(dto.getUserBaseId(),
                            dto.getBeginTime(), dto.getEndTime(),PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()),
                            dto.getChannelId()));
                }else {
                    //贷记卡+云闪付
                    reachAmtVO.setReachAmt(transactionPayTransactionMapper.yxyEposReachAmtByChannelId(dto.getUserBaseId(),
                            dto.getBeginTime(), dto.getEndTime(),PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()),
                            dto.getChannelId()));
                }

            }

        }
        KLog.info("[实时达标金额]出参:{}, 入参:{}", reachAmtVO.toJSON(), dto.toJSON());
        return Result.builder().success(reachAmtVO);
    }

    @Override
    public Result<ReachAmtVO> discountTradeAmt(ReachAmtDTO dto) {
        KLog.info("[获取交易额]入参:{}", dto.toJSON());
        ReachAmtVO reachAmtVO = new ReachAmtVO();
        reachAmtVO.setReachAmt(transactionPayTransactionMapper.discountTradeAmt(dto.getUserBaseId(), PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()), dto.getChannelId()));
        return Result.builder().success(reachAmtVO);
    }

    /**
     * 查询归属于该盟友的机具中交易笔数最高的
     * @param dto
     * @return
     */
    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<TradeCountVO> tradeCount(TradeCountDTO dto) {

        KLog.info("查询交易笔数入参:{}", dto.toJSON());
        TradeCountVO tradeCountVO = null;
        if (StringUtils.isNotBlank(dto.getTerminalSn())) {
            tradeCountVO = transactionPayTransactionMapper.countTradeM40ByTerminalSn(PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()), dto);
        }else {
            tradeCountVO = transactionPayTransactionMapper.countTradeM40ByAlly(PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()), dto);
        }

        if(Objects.isNull(tradeCountVO)){
            tradeCountVO=new TradeCountVO();
            if (StringUtils.isBlank(dto.getTerminalSn())) {
             Terminal21Example terminal21Example =new Terminal21Example();
                terminal21Example.createCriteria().andBindUserBaseIdEqualTo(dto.getUserBaseId())
                        .andPlatNoEqualTo(PlatNoEnums.YXY.getCode()).andChannelIdEqualTo(dto.getChannelId());
                List<Terminal21> terminal21s = terminal21Mapper.selectByExample(terminal21Example);
                if (CollectionUtils.isNotEmpty(terminal21s)) {
                    tradeCountVO.setTerminalSn(terminal21s.get(0).getTerminalSn());
                }
            }else {
                tradeCountVO.setTerminalSn(dto.getTerminalSn());
            }
        }
        KLog.info("查询交易笔数返回: {},入参:{}",tradeCountVO, dto.toJSON());
        return Result.builder().success(tradeCountVO);
    }

    /**
     * 违激活金额
     */
    @Override
    public Result<ActivateAmtVO> activateAmount(ActivateAmtDTO dto) {
        KLog.info("[违激活金额]入参:{}", dto.toJSON());
        ActivateAmtVO activateAmtVO = new ActivateAmtVO();
        if (PlatNoEnums.KLKS.isEquals(dto.getPlatNo())) {
            if (ChannelIdEnums.epos.isEquals(dto.getChannelId())){
                activateAmtVO.setActivateAmt(transactionPayTransactionMapper.eposActivateAmt(dto.getUserBaseId(), dto.getBeginTime(), dto.getEndTime(), PayTransactionConfig.getTransTableIndex(dto.getUserBaseId())));
            }
        }
        KLog.info("[违激活金额]出参:{}, 入参:{}", activateAmtVO.toJSON(), dto.toJSON());
        return null;
    }

    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<AmountVO> userTotalAmount(QueryUserTotalAmountDTO dto) {
        KLog.info("[查询用户总交易额]入参:{}", dto.toString());
        if (!ChannelIdEnums.isValidEnumList(dto.getChannelIds())) {
            return Result.builder().fail(BizCodeMessages.VALIDATOR_ERR,"channelId校验失败");
        }
        int transTableIndex = PayTransactionUtil.getTransTableIndex(dto.getUserBaseId());
        BigDecimal bigDecimal = transactionPayTransactionMapper.queryTotalAmountContainPledge(dto, transTableIndex);

        AmountVO vo = new AmountVO();
        vo.setMonthAmount(bigDecimal);
        KLog.info("[查询用户总交易额]出参:{}, 入参:{}", vo.toJSON(), dto.toJSON());
        return Result.builder().success(vo);
    }

    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<List<UsersAmountVO>> usersTotalAmount(QueryUsersTotalAmountDTO dto) {

        KLog.info("[查询多个用户总交易额]入参:{}", dto.toString());
        if (!ChannelIdEnums.isValidEnumList(dto.getChannelIds())) {
            return Result.builder().fail(BizCodeMessages.VALIDATOR_ERR,"channelId校验失败");
        }
        List<UsersAmountVO> usersAmountVOS = new ArrayList<>();
        for (String userBaseId : dto.getUserBaseIds()) {
            UsersAmountVO usersAmountVO =new UsersAmountVO();
            QueryUserTotalAmountDTO queryUserTotalAmountDTO = new QueryUserTotalAmountDTO();
            queryUserTotalAmountDTO.setUserBaseId(userBaseId);
            queryUserTotalAmountDTO.setPlatNo(dto.getPlatNo());
            queryUserTotalAmountDTO.setChannelIds(dto.getChannelIds());

            int transTableIndex = PayTransactionUtil.getTransTableIndex(userBaseId);
            usersAmountVO.setTotalAmount(transactionPayTransactionMapper
                    .queryTotalAmountContainPledge(queryUserTotalAmountDTO,transTableIndex));
            usersAmountVO.setUserBaseId(userBaseId);
            usersAmountVOS.add(usersAmountVO);
        }

        KLog.info("[查询多个用户总交易额]出参:{}, 入参:{}", usersAmountVOS.toString(), dto.toJSON());
        return Result.builder().success(usersAmountVOS);
    }

    /**
     * 多个用户当月总交易额
     *
     * @param dto
     */
    @Override
    @RoutingDataSource(DataSources.SLAVE_DB)
    public Result<List<UsersAmountVO>> usersCurrentMonthTotalAmount(QueryUsersCurrentMonthTotalAmountDTO dto) {
        KLog.info("[查询多个用户当月总交易额]入参:{}", dto.toString());
        if (!ChannelIdEnums.isValidEnumList(dto.getChannelIds())) {
            return Result.builder().fail(BizCodeMessages.VALIDATOR_ERR,"channelId校验失败");
        }
        List<UsersAmountVO> usersAmountVOS = new ArrayList<>();
        for (String userBaseId : dto.getUserBaseIds()) {
            QueryMonthListAmountDTO queryMonthAmountDTO = new QueryMonthListAmountDTO();
            queryMonthAmountDTO.setUserBaseId(userBaseId);
            queryMonthAmountDTO.setPlatNo(dto.getPlatNo());
            queryMonthAmountDTO.setChannelIds(dto.getChannelIds());
            List<String> monthList = new ArrayList<>();
            monthList.add(dto.getCurrentMonth());
            queryMonthAmountDTO.setMonthList(monthList);
            UsersAmountVO usersAmountVO = new UsersAmountVO();
            usersAmountVO.setUserBaseId(userBaseId);
            usersAmountVO.setTotalAmount(transactionPayTransactionMapper
                    .queryCurrentMonthAmountContainPledge(queryMonthAmountDTO, PayTransactionUtil.getTransTableIndex(userBaseId)));
            usersAmountVOS.add(usersAmountVO);
        }


        KLog.info("[查询多个用户当月总交易额]出参:{}, 入参:{}", usersAmountVOS.toString(), dto.toJSON());
        return Result.builder().success(usersAmountVOS);
    }

    @Override
    public Result<List<MonthAmountVO>> monthsAmountByAlly(QueryMonthListAmountByAllyDTO dto) {
        KLog.info("[单个用户多个月交易额 - 通讯录点进商户详情 -按机具归属盟友查询]入参:{}", dto.toString());
        List<String> terminalSnLists = getAllyTerminalSnByAllyUserBaseId(dto.getUserBaseId(), dto.getAllyUserBaseId(), dto.getChannelId());
        List<MonthAmountVO> monthAmountVOList = new ArrayList<>();
        if (Objects.nonNull(terminalSnLists) && CollectionUtils.isNotEmpty(terminalSnLists)) {
            dto.setTerminalSnList(terminalSnLists);
            monthAmountVOList = transactionPayTransactionMapper.queryMonthsAmountBySns(dto, PayTransactionUtil.getTransTableIndex(dto.getUserBaseId()));
        }
        KLog.info("[单个用户多个月交易额 - 通讯录点进商户详情 -按机具归属盟友查询]出参:{}, 入参:{}", monthAmountVOList.toString(), dto.toJSON());
        return Result.builder().success(monthAmountVOList);
    }

    @Override
    public Result<AmountVO> userTotalAmountByAlly(QueryUserTotalAmountByAllyDTO dto) {
        KLog.info("[单个用户总交易额 - 通讯录点进商户详情 -按机具归属盟友查询]入参:{}", dto.toString());
        List<String> terminalSnLists = getAllyTerminalSnByAllyUserBaseId(dto.getUserBaseId(), dto.getAllyUserBaseId(), dto.getChannelId());
        AmountVO amountVO = new AmountVO();
        if (Objects.nonNull(terminalSnLists) && CollectionUtils.isNotEmpty(terminalSnLists)) {
            dto.setTerminalSnList(terminalSnLists);
            BigDecimal amount = transactionPayTransactionMapper.queryUserAmountBySns(dto, PayTransactionUtil.getTransTableIndex(dto.getUserBaseId()));
            amountVO.setMonthAmount(amount);
        }
        KLog.info("[单个用户总交易额 - 通讯录点进商户详情 -按机具归属盟友查询]出参:{}, 入参:{}", amountVO.toString(), dto.toJSON());
        return Result.builder().success(amountVO);
    }

    @Override
    public Result<List<UsersAmountVO>> usersTotalAmountByAlly(QueryUsersTotalAmountByAllyDTO dto) {
        KLog.info("[多个用户总交易额 -通讯录商户列表 -按机具归属盟友查询]入参:{}", dto.toString());
        List<UsersAmountVO> usersAmountVOList=new ArrayList<>();
        dto.getUserIdDTOS().forEach(user->{
            List<String> terminalSnLists = getAllyTerminalSnByAllyUserBaseId(user.getUserBaseId(), user.getAllyUserBaseId(), dto.getChannelId());
            UsersAmountVO usersAmountVO = new UsersAmountVO();
            usersAmountVO.setUserBaseId(user.getUserBaseId());
            usersAmountVO.setTotalAmount(BigDecimal.ZERO);
            if (Objects.nonNull(terminalSnLists) && CollectionUtils.isNotEmpty(terminalSnLists)) {
                QueryUserTotalAmountByAllyDTO queryDto=new QueryUserTotalAmountByAllyDTO();
                queryDto.setUserBaseId(user.getUserBaseId());
                queryDto.setAllyUserBaseId(user.getAllyUserBaseId());
                queryDto.setPlatNo(PlatNoEnums.YXY.getCode());
                queryDto.setChannelId(dto.getChannelId());
                queryDto.setTerminalSnList(terminalSnLists);
                BigDecimal amount = transactionPayTransactionMapper.queryUserAmountBySns(queryDto, PayTransactionUtil.getTransTableIndex(user.getUserBaseId()));
                usersAmountVO.setTotalAmount(amount);
            }
            usersAmountVOList.add(usersAmountVO);
        });
        KLog.info("[多个用户总交易额 -通讯录商户列表 -按机具归属盟友查询]出参:{}, 入参:{}", usersAmountVOList.toString(), dto.toJSON());
        return Result.builder().success(usersAmountVOList);
    }

    @Override
    public Result<List<UsersAmountVO>> usersCurrentMonthTotalAmountByAlly(QueryUsersCurrentMonthTotalAmountByAllyDTO dto) {
        KLog.info("[多个用户当月总交易额 -通讯录商户列表 -按机具归属盟友查询]入参:{}", dto.toString());
        List<UsersAmountVO> usersAmountVOList=new ArrayList<>();
        dto.getUserIdDTOS().forEach(user->{
            List<String> terminalSnLists = getAllyTerminalSnByAllyUserBaseId(user.getUserBaseId(), user.getAllyUserBaseId(), dto.getChannelId());
            UsersAmountVO usersAmountVO = new UsersAmountVO();
            usersAmountVO.setUserBaseId(user.getUserBaseId());
            usersAmountVO.setTotalAmount(BigDecimal.ZERO);
            if (Objects.nonNull(terminalSnLists) && CollectionUtils.isNotEmpty(terminalSnLists)) {
                QueryUserTotalAmountByAllyDTO queryDto=new QueryUserTotalAmountByAllyDTO();
                queryDto.setUserBaseId(user.getUserBaseId());
                queryDto.setAllyUserBaseId(user.getAllyUserBaseId());
                queryDto.setPlatNo(PlatNoEnums.YXY.getCode());
                queryDto.setChannelId(dto.getChannelId());
                queryDto.setTerminalSnList(terminalSnLists);
                queryDto.setMonth(dto.getCurrentMonth());
                BigDecimal amount = transactionPayTransactionMapper.queryUserAmountBySns(queryDto, PayTransactionUtil.getTransTableIndex(user.getUserBaseId()));
                usersAmountVO.setTotalAmount(amount);
            }
            usersAmountVOList.add(usersAmountVO);
        });
        KLog.info("[多个用户当月总交易额 -通讯录商户列表 -按机具归属盟友查询]出参:{}, 入参:{}", usersAmountVOList.toString(), dto.toJSON());
        return Result.builder().success(usersAmountVOList);
    }

    /**
     * 通过归属盟友用户ID查询 交易归属的SN号
     * @param userBaseId 商户用户ID
     * @param allyUserBaseId 盟友用户ID
     * @param channelId 渠道ID
     * @return 交易归属的SN号
     */
    private List<String> getAllyTerminalSnByAllyUserBaseId(String userBaseId, String allyUserBaseId, Short channelId) {
        TerminalHistory21Example terminalHistory21Example=new TerminalHistory21Example();
        terminalHistory21Example.createCriteria().andBindUserBaseIdEqualTo(userBaseId)
                .andAllyUserBaseIdEqualTo(allyUserBaseId).andTerminalHistoryStatusEqualTo(TerminalEnum.Status.bind.getCode());
        List<TerminalHistory21> history21List= terminalHistory21Mapper.selectByExample(terminalHistory21Example);
        List<String> terminalSnLists = null;
        if (CollectionUtils.isNotEmpty(history21List)) {
            terminalSnLists = history21List.stream().filter(item -> allyUserBaseId.equals(item.getAllyUserBaseId())).map(TerminalHistory21::getTerminalSn).collect(Collectors.toList());
        } else {
            //划拨未接收时激活返现归划拨人,机具历史表记录的机具归属为划拨人. 接收时改变商户和机具归属为接收人(即分润归属接收人). 通过历史表查不到接收人故增加此逻辑
            Terminal21Example terminal21Example = new Terminal21Example();
            terminal21Example.createCriteria().andBindUserBaseIdEqualTo(userBaseId).andAllyUserBaseIdEqualTo(allyUserBaseId).andTerminalStatusEqualTo(TerminalEnum.Status.bind.getCode());
            List<Terminal21> terminal21List = terminal21Mapper.selectByExample(terminal21Example);
            terminalSnLists = terminal21List.stream().map(Terminal21::getTerminalSn).collect(Collectors.toList());
        }
        if(CollectionUtil.isNotEmpty(terminalSnLists)){
            //机具号为OQR EQR开头, 该类机具的交易额计算到第一个激活的机具上
            UserMerchantRecommend21Example userMerchantRecommend21Example = new UserMerchantRecommend21Example();
            userMerchantRecommend21Example.createCriteria().andUserBaseIdEqualTo(userBaseId).andBelongMerchantUserBaseIdEqualTo(allyUserBaseId);
            List<UserMerchantRecommend21> userMerchantRecommend21List = userMerchantRecommend21Mapper.selectByExample(userMerchantRecommend21Example);
            if (CollectionUtils.isNotEmpty(userMerchantRecommend21List)) {
                //所有发生过交易的机具号
                List<String> terminalSnList = transactionPayTransactionMapper.getTerminalSnByUserBaseIdAndChannelId(userBaseId, channelId, PlatNoEnums.YXY.getCode(), PayTransactionUtil.getTransTableIndex(userBaseId));
                terminalSnList = terminalSnList.stream().filter(item -> item.startsWith("EQR") || item.startsWith("OQR")).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(terminalSnList)) {
                    terminalSnLists.addAll(terminalSnList);
                }
            }
        }
        return terminalSnLists;
    }

    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<List<MonthAmountVO>> monthsAmount(QueryMonthListAmountDTO dto) {
        KLog.info("[查询用户多个月总交易额]入参:{}", dto.toString());
        if (!ChannelIdEnums.isValidEnumList(dto.getChannelIds())) {
            return Result.builder().fail(BizCodeMessages.VALIDATOR_ERR,"channelId校验失败");
        }
        int transTableIndex = PayTransactionUtil.getTransTableIndex(dto.getUserBaseId());
        List<MonthAmountVO> monthAmountVOS = transactionPayTransactionMapper.queryMonthsAmountContainPledge(dto, transTableIndex);
        List<String> voMonths = new ArrayList<>();
        for (MonthAmountVO monthAmountVO : monthAmountVOS) {
            voMonths.add(monthAmountVO.getMonth());
        }
        for (String month : dto.getMonthList()) {
            if (!voMonths.contains(month)) {
                MonthAmountVO monthAmountVO = new MonthAmountVO();
                monthAmountVO.setMonthAmount(BigDecimal.ZERO);
                monthAmountVO.setMonth(month);
                monthAmountVOS.add(monthAmountVO);
            }
        }
        KLog.info("[查询用户多个月总交易额]出参:{}, 入参:{}", monthAmountVOS.toString(), dto.toJSON());
        return Result.builder().success(monthAmountVOS);
    }

    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<BigDecimal> yxyAmtM40( TradeCountDTO dto) {
        KLog.info("查询M40优惠交易金额,入参:{}",dto.toJSON());
        BigDecimal decimal = transactionPayTransactionMapper.yxyAmtM40(PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()),
                dto);
        KLog.info("查询M40优惠交易金额,出参:{},入参:{}",decimal,dto.toJSON());
        return Result.builder().success(decimal);
    }

    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<BigDecimal> yxyAmtM40All( TradeCountDTO dto) {
        KLog.info("查询M40交易金额,入参:{}",dto.toJSON());
        BigDecimal decimal = transactionPayTransactionMapper.yxyAmtM40All(PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()),
                dto);
        KLog.info("查询M40交易金额,出参:{},入参:{}",decimal,dto.toJSON());
        return Result.builder().success(decimal);
    }

    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<BigDecimal> yxyAmtAllCard( TradeCountDTO dto) {
        KLog.info("查询交易笔数,入参:{}",dto.toJSON());
        BigDecimal decimal = transactionPayTransactionMapper.yxyAmtAllCard(PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()),
                dto);
        KLog.info("查询交易笔数,出参:{},入参:{}",decimal,dto.toJSON());
        return Result.builder().success(decimal);
    }

    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<Integer> transactionCount( QueryTradeCountDTO dto) {

        KLog.info("查询交易笔数,入参:{}",dto.toJSON());
        Integer transactionCount = transactionPayTransactionMapper.transactionCount(
                PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()), dto);
        KLog.info("查询交易笔数,出参:{},入参:{}",transactionCount,dto.toJSON());
        return Result.builder().success(transactionCount);
    }

    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<Integer> transactionCountM40( QueryTradeCountDTO dto) {

        KLog.info("查询交易笔数M40,入参:{}",dto.toJSON());
        Integer transactionCount = transactionPayTransactionMapper.transactionCountM40(
                PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()), dto);
        KLog.info("查询交易笔数M40,出参:{},入参:{}",transactionCount,dto.toJSON());
        return Result.builder().success(transactionCount);
    }

    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<PayTransaction> queryPledge(@Valid QueryPledgeDTO dto) {

        KLog.info("查询押金交易,入参:{}",dto.toJSON());
        if(ChannelIdEnums.yxy_jl_m40.isEquals(dto.getChannelId())){
            return Result.builder().fail(BizCodeMessages.VALIDATOR_ERR,"M40无押金交易");
        }

        PayTransaction payTransaction = new PayTransaction();

        if (ChannelIdEnums.yxy_lkl_p42.getCode().equals(dto.getChannelId())){
            payTransaction = transactionPayTransactionMapper.selectYxyP42PledgePayTransaction(dto.getUserBaseId(),
                    PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()));
        }else {
            payTransaction = transactionPayTransactionMapper.selectYxyPledgeAmount(dto.getUserBaseId(),
                    PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()), dto.getChannelId());
        }

        return Result.builder().success(payTransaction);
    }


    @RoutingDataSource(DataSources.SLAVE_DB)
    @Override
    public Result<PayTransaction> queryTransactionByOrderNo(@Valid QueryTransactionDTO dto) {

        KLog.info("根据订单号查询交易,入参:{}",dto.toJSON());

        PayTransaction payTransaction = transactionPayTransactionMapper
                .getByOrderNo(PayTransactionConfig.getTransTableIndex(dto.getUserBaseId()), dto.getOrderNo());


        return Result.builder().success(payTransaction);
    }

}
